package cn.walmt.interceptor;

import cn.walmt.entity.User;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.GsonUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by walmt on 2017/6/9.
 */
public class UserInterceptor extends HandlerInterceptorAdapter {

    private static String[] excludedUrlPrefix = {"/user/login", "/upload", "/store"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*if (request.getSession().getAttribute("user") == null) {
            User user = new User();
            user.setId(1);
            user.setOpenid("1");
            user.setSex(true);
            user.setHeadUrl("1");
            request.getSession().setAttribute("user", user);
        }
        return true;*/

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json");

        String path = request.getServletPath();

        if (isExcludedUrlPrefix(path)) {
            return super.preHandle(request, response, handler);
        }

        User user = (User) request.getSession().getAttribute("user");

        if (user == null) {
            PrintWriter out = response.getWriter();
            out.print(GsonUtil.getErrorJson("请先登录"));
            out.close();
            return false;
        }

        return super.preHandle(request, response, handler);
    }

    private boolean isExcludedUrlPrefix(String path) {
        for (String prefix : excludedUrlPrefix) {
            if (path.startsWith(prefix))
                return true;
        }
        return false;
    }
}
